package com.atguigu.tingshu.user.service.impl;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.IdUtil;
import com.atguigu.tingshu.common.constant.RedisConstant;
import com.atguigu.tingshu.common.rabbit.constant.MqConst;
import com.atguigu.tingshu.common.rabbit.service.RabbitService;
import com.atguigu.tingshu.model.user.UserInfo;
import com.atguigu.tingshu.user.mapper.UserInfoMapper;
import com.atguigu.tingshu.user.service.UserInfoService;
import com.atguigu.tingshu.vo.user.UserInfoVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
@SuppressWarnings({"all"})
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {

	@Autowired
	private UserInfoMapper userInfoMapper;

	@Autowired
	private WxMaService wxMaService;

	@Autowired
	private RedisTemplate redisTemplate;

	@Autowired
	private RabbitService rabbitService;

	/**
	 * 小程序授权登录
	 * @param code
	 * @return
	 */
	@Override
	@SneakyThrows
	public Map<String,String> login(String code) {

		//1.请求微信认证接口，获取用户信息
		WxMaJscode2SessionResult sessionInfo = wxMaService.getUserService().getSessionInfo(code);

		//创建封装对象
		Map<String,String> resultMap=new HashMap<>();

		//2.根据返回的信息，判断登录是否成功
		if(sessionInfo!=null){
			//获取认证凭证
			String openid = sessionInfo.getOpenid();
			//3.根据用户的openId,查询用户信息
			UserInfo userInfo = userInfoMapper.selectOne(new QueryWrapper<UserInfo>().eq("wx_open_id", openid));

			if(userInfo==null){
				//不存在  第一次 注册
				userInfo=new UserInfo();
				userInfo.setWxOpenId(openid);
				userInfo.setNickname("书友："+ IdUtil.getSnowflakeNextIdStr());
				userInfo.setAvatarUrl("https://www.flavorbio.com/uploads/image/20191126/400370101c0e579a7896d5caf5eeffa6.png");
				userInfoMapper.insert(userInfo);

				//初始化账户信息
				rabbitService.sendMessage(
						MqConst.EXCHANGE_USER,
						MqConst.ROUTING_USER_REGISTER,
						userInfo.getId()
				);

			}
			//4.生成token
			String token =IdUtil.fastUUID();
			//定义存储key
			String loginKey= RedisConstant.USER_LOGIN_KEY_PREFIX+token;
			//屏蔽敏感信息
			UserInfoVo userInfoVo = BeanUtil.copyProperties(userInfo, UserInfoVo.class);

			//5.存储到共享区域redis
			redisTemplate.opsForValue().set(loginKey,userInfoVo,RedisConstant.USER_LOGIN_KEY_TIMEOUT, TimeUnit.SECONDS);
			//6.封装返回结果
			resultMap.put("token",token);


		}


		return resultMap;
	}

	/**
	 * 更新用户信息
	 * @param userInfoVo
	 */
	@Override
	public void updateUser(UserInfoVo userInfoVo,String token) {

		//创建修改实体
		UserInfo userInfo = BeanUtil.copyProperties(userInfoVo, UserInfo.class);
		userInfo.setUpdateTime(new Date());

		userInfoMapper.updateById(userInfo);

		//同步redis
		String loginKey= RedisConstant.USER_LOGIN_KEY_PREFIX+token;
		//屏蔽敏感信息
		 BeanUtils.copyProperties(userInfo, userInfoVo);

		//5.存储到共享区域redis
		redisTemplate.opsForValue().set(loginKey,userInfoVo,RedisConstant.USER_LOGIN_KEY_TIMEOUT, TimeUnit.SECONDS);

	}


}
